#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import os
import sys
import subprocess
import requests
import re
import time
import threading
from tkinter import *
from threading import Thread
from typing import Optional
from tkinter.font import Font
from tkinter.ttk import *
# Usage:showinfo/warning/error,askquestion/okcancel/yesno/retrycancel
from tkinter.messagebox import *
# from tkinter import filedialog  #.askopenfilename()
# from tkinter import simpledialog  #.askstring()
# ============================================================================
from UI import Application_ui
from tkinter import filedialog, messagebox
from Loop_download_list_thread import Loop_download_list_thread

g_tt = None
g_run_stutus = False

def get_download_address(url: str) -> str:
    """
    从给定的页面URL中提取真实的下载地址

    参数:
        url (str): 包含下载链接的页面URL
        例如:https://fuckingfast.co/omol7vklou0b#File_Name-part01.rar

    返回:
        str: 提取出的真实下载地址，如果提取失败则返回空字符串
    """
    response = requests.get(url)
    if response.status_code == 200:
        pattern = r"window\.open\(\"(http.*)\"\)"
        matches = re.findall(pattern, response.text)
        return matches[0]
    else:
        return ""


def send_cmd(idm_path: str, save_path: str, address: str):
    filename = address.split('#')[-1]
    url = get_download_address(address)
    if url != "":
        cmd = idm_path + " /d "+url+" /f "+filename + " /p "+save_path+" /n"
        subprocess.run(cmd)
        return save_path + "\\" + filename
    return ""


def center_window(window, width, height):
    """将指定窗口居中显示"""
    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()
    position_x = (screen_width // 2) - (width // 2)
    position_y = (screen_height // 2) - (height // 2)
    window.geometry(f"{width}x{height}+{position_x}+{position_y}")

class Application(Application_ui):
    # 这个类实现具体的事件处理回调函数。界面生成代码在Application_ui中。
    def __init__(self, master=None):
        super().__init__(master)
        center_window(self.master, 800, 600)
        self.txt_dl_list.delete("1.0", "end")
        self.txt_dl_status.delete("1.0", "1.3")
        self.btn_stop.config(state="disabled")
        self.Loop_download_list_thread : Optional[Loop_download_list_thread] = None

        self.txt_IDMVar.set(
            "C:\\Program Files (x86)\\Internet Download Manager\\IDMan.exe")
        self.txt_saveVar.set("E:\\ISO")
        # self.txt_dl_list.insert(
        #     "1.0",
        #     "https://fuckingfast.co/h4x8c4ebu0p7#WUCHANG_Fallen_Feathers_--_fitgirl-repacks.site_--_.part31.rar"
        # )

    def btn_IDM_Cmd(self, event=None):
        # 设置文件选择对话框的初始目录和筛选条件
        file_path = filedialog.askopenfilename(
            title="选择 IDM 的 idman.exe 文件",
            # 常见的 IDM 安装路径
            initialdir="C:/Program Files (x86)/Internet Download Manager",
            filetypes=[("EXE 文件", "idman.exe")]
        )
        if file_path:
            self.txt_IDMVar.set(file_path)

    def btn_save_Cmd(self, event=None):
        self.txt_saveVar.set(filedialog.askdirectory())

    def btn_start_Cmd(self, event=None):
        idm_path = self.txt_IDMVar.get()
        if idm_path == "":
            messagebox.showwarning("提示", "请选择IDM路径")
            return

        save_path = self.txt_saveVar.get()
        if save_path == "":
            messagebox.showwarning("提示", "请选择保存路径")
            return

        dl_list = self.txt_dl_list.get("1.0", "end")
        if dl_list == "\n":
            messagebox.showwarning("提示", "请输入下载地址")
            return

        self.btn_start.config(state="disabled")
        self.btn_stop.config(state="normal")

        dl_lists = [item for item in dl_list.split("\n") if item]
        if dl_lists[0] == "":
            print("无下载地址")
            return

        self.Loop_download_list_thread = Loop_download_list_thread(self,dl_lists,idm_path, save_path)
        self.Loop_download_list_thread.start()
        
    def btn_stop_Cmd(self, event=None):
        if self.Loop_download_list_thread is not None:
            self.Loop_download_list_thread.stop()
            if self.Loop_download_list_thread.Loop_exists_file_thread is not None:
                self.Loop_download_list_thread.Loop_exists_file_thread.stop()
    
        self.btn_start.config(state="normal")
        self.btn_stop.config(state="disabled")

if __name__ == "__main__":
    top = Tk()
    Application(top).mainloop()
